package com.znsd.zl.house.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.znsd.zl.house.dao.RentDao;
import com.znsd.zl.house.entity.HouseImage;
import com.znsd.zl.house.entity.RentEntity;
import com.znsd.zl.house.entity.vo.RentRespVO;
import com.znsd.zl.house.service.DictItemServiceFeign;
import com.znsd.zl.house.service.IRentService;
import com.znsd.zl.house.utils.ConditionPageUtils;
import com.znsd.zl.utils.PageUtils;
import com.znsd.zl.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName RentServiceImpl
 * @Description 描述
 * @author zhubin
 * @date 2020-08-21 10:49:33
 * @Version v1.0
 */
@SuppressWarnings("all")
@Slf4j
@Service
public class RentServiceImpl extends ServiceImpl<RentDao, RentEntity> implements IRentService {
	@Autowired
	DictItemServiceFeign dictItemServiceFeign;
	@Value("${facility}")
	String facility;

	// 条件查询分页
	@Override
	public PageUtils conditionQueryPage(Map<String,Object> params, RentRespVO house) {
		// 移除map多余数据
		removeProperty(params);
		// 获取分页的参数
		int[] pageAndLimit = ConditionPageUtils.getPageAndLimit(params);
		Integer startNum = pageAndLimit[0];
		Integer size = pageAndLimit[1];
		// 获取房屋数量条件
		String roomNumber = String.valueOf(params.remove("roomNumber"));
		log.info("封装对象===="+house);
		log.info(params+"  "+startNum+"  "+size + "房间数=="+roomNumber);
		// 计算从那开始
		Integer pageNum = (startNum -1) * size;
		// 进行查询
		List<RentRespVO> rents = this.baseMapper.conditionQueryPage(params, pageNum, size,house);

		// 没有数据就随机推送
		if (rents.size() == 0 && params.get("rent.house_id") == null /*&& !StringUtils.isEmpty(house.getVillageName())*/) {
			return push(null,startNum,size);
		}
		// 记录原来数据数量
		Integer beginNum = rents.size();
		// 组合条件查询
		for (int i = 0; i < rents.size(); i++) {
			String[] room = rents.get(i).getHouseType().split(",");
			rents.get(i).setHouseTypeName(room[0]+"室"+room[1]+"厅"+room[2]+"卫");
			if (roomNumber != null && !"null".equals(roomNumber) && !"".equals(roomNumber)) {
				if (room.length >= 1 && roomNumber.toLowerCase().contains("n")) {
					int number = Integer.parseInt(roomNumber.substring(0,roomNumber.toLowerCase().indexOf("n")));
					if (number <= Integer.parseInt(room[0])) {
						continue;
					}
				} else if (room.length >= 1 && room[0].trim().equals(roomNumber)) {
					continue;
				}
				rents.remove(i);
				i--;
			}
		}
		// 防止房屋个数条件过滤完没有数据
		if (rents.size() == 0 && params.get("rent.house_id") == null /*&& !StringUtils.isEmpty(house.getVillageName())*/) {
			return push(null,startNum,size);
		}
		// 计算过滤的条件，用来重新计算总数
		Integer removeNum = Math.abs(rents.size() - beginNum);
		// 循环查询，减少数据库的操作
		setData(rents);
		Integer count = conditionQueryTotal(params,house)-removeNum;
		//封装分页数据
		return ConditionPageUtils.pageData(startNum,size,rents,count);
	}


	// 条件查询所有的出租房源信息
	@Override
	public PageUtils conditionQueryAll(Map<String,Object> params, RentRespVO house) {
		// 移除map多余数据
		removeProperty(params);
		// 获取分页的参数
		int[] pageAndLimit = ConditionPageUtils.getPageAndLimit(params);
		Integer startNum = pageAndLimit[0];
		Integer size = pageAndLimit[1];
		// 获取房屋数量条件
		String roomNumber = String.valueOf(params.remove("roomNumber"));
		log.info("封装对象===="+house);
		log.info(params+"  "+startNum+"  "+size + "房间数=="+roomNumber);
		// 计算从那开始
		Integer pageNum = (startNum -1) * size;
		// 进行查询
		List<RentRespVO> rents = this.baseMapper.conditionQueryAll(params, pageNum, size,house);

		// 记录原来数据数量
		Integer beginNum = rents.size();
		// 组合条件查询
		for (int i = 0; i < rents.size(); i++) {
			String[] room = rents.get(i).getHouseType().split(",");
			rents.get(i).setHouseTypeName(room[0]+"室"+room[1]+"厅"+room[2]+"卫");
			if (roomNumber != null && !"null".equals(roomNumber) && !"".equals(roomNumber)) {
				if (room.length >= 1 && roomNumber.toLowerCase().contains("n")) {
					int number = Integer.parseInt(roomNumber.substring(0,roomNumber.toLowerCase().indexOf("n")));
					if (number <= Integer.parseInt(room[0])) {
						continue;
					}
				} else if (room.length >= 1 && room[0].trim().equals(roomNumber)) {
					continue;
				}
				rents.remove(i);
				i--;
			}
		}
		// 计算过滤的条件，用来重新计算总数
		Integer removeNum = Math.abs(rents.size() - beginNum);
		// 循环查询，减少数据库的操作
		setData(rents);
		Integer count = this.baseMapper.conditionQueryAllTotal(params,house)-removeNum;
		//封装分页数据
		return ConditionPageUtils.pageData(startNum,size,rents,count);
	}




	// 条件查询总数
	@Override
	public Integer conditionQueryTotal(Map<String,Object> params, RentRespVO house) {
		// 移除map多余数据
		removeProperty(params);
		return this.baseMapper.conditionQueryTotal(params,house);
	}


	// 推送
	@Override
	public PageUtils push(String districtName, Integer startNum, Integer size) {
		// 默认分页数
		if (startNum == null || startNum < 0) { startNum = 1; }
		if (size == null || size < 0) {
			size = 10;
		}
		// 计算从那开始
		Integer pageNum = (startNum -1) * size;
		List<RentRespVO> rents = this.baseMapper.push(districtName, pageNum, size);
		setData(rents);
		return ConditionPageUtils.pageData(startNum,size,rents,10);
	}

	// 根据房屋id查询图片
	@Override
	public List<String> findHouseImage(Integer houseId) {
		return this.baseMapper.findHouseImage(houseId);
	}

	@Override
	public Map findHouseProfit(Integer rentId) {
		return getBaseMapper().findHouseProfit(rentId);
	}

	@Override
	public List<HouseImage> findHouseImages(Integer houseId) {
		return this.baseMapper.findHouseImages(houseId);
	}

	@Override
	public void deleteHouseImage(Integer imageId) {
		this.baseMapper.deleteHouseImage(imageId);
	}


	// 移除map范围查询字段
	public void removeProperty(Map<String,Object> params){
		params.remove("greaterThan");
		params.remove("lessThan");
		params.remove("lowPrice");
		params.remove("highPrice");
		params.remove("villageName");
	}

	// 给租房信息填充电器
	public void setData(List<RentRespVO> rents){
		// 获取数据并转换
		List dictItems  = null;
		try {
			// 调用字典服务的方法
			R r = dictItemServiceFeign.queryTextByDictType(facility);
			dictItems = (List) r.get("data");
		} catch (Exception e) {
			log.error("rentService request dictItemServiceFeign error {}",e.toString());
		}

		for (RentRespVO rent : rents) {
			String[] room = rent.getHouseType().split(",");
			rent.setHouseTypeName(room[0]+"室"+room[1]+"厅"+room[2]+"卫");
			StringBuilder sb = new StringBuilder();
			if (rent.getFacility() == null) {continue;}
			String[] facilitys = rent.getFacility().split(",");
			if (facilitys.length == 0) {continue;}
			// 一个一个查询匹配
			for (String facility : facilitys) {
				// 防止 数据字典死亡
				if (dictItems == null) {break;}
				for (Object dictItem : dictItems) {
					LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) dictItem;
					if (facility.trim().equals(map.get("id")+"")) {
						sb.append(map.get("dictItemText")+",");
						break;
					}
				}
			}
			rent.setFacilityName(sb.toString().length() >=1 ? sb.toString().substring(0,sb.toString().length() - 1) : null);
		}
	}

	@Override
	/**
	 * 根据用户Id查询用户的租房信息
	 * @param userId
	 * @return
	 */
	public List<RentEntity> findUserHouse(Integer userId){
		 return baseMapper.findUserHouse(userId);
	}

}
